var list = $(".list");
var editBtn = $(".edit-btn");
var sendBtn = $(".send-btn");
var userSumbit = $(".user-sumbit");
var userCancel = $(".user-cancel");
var editContent = $(".edit-content");
var sendContent = $(".send-content");
var ownerSumbit = $(".submit");
var deleteBtn = $(".delete");

getData();
getMessage();
// 获取留言
function getData() {
  $.ajax({
    url: "http://localhost:3000/db",
    type: "GET",
    success: function (data) {
      // 将模板添加到页面中
      list.html(template("tem", data));
      // console.log(data);
      // 给删除按钮绑定事件
      deleteData();
      // 获取留言数量
      $(".leave-title").text(`留言(${data.comments.length})`);
    }
  });

}
// 获取寄语
function getMessage() {
  $.ajax({
    url: "http://localhost:3000/db",
    type: "GET",
    success: function (data) {
      // console.log(data.message.info);
      $(".exhibition").text(data.message.info);
    }
  })
}
// 给删除按钮注册绑定
function deleteData() {
  $(".message-right .delete").click(function () {
    var temp = $(this).parents(".message-content");
    var uid = temp.attr("uid");
    $.ajax({
      url: "http://localhost:3000/comments/" + uid,
      type: "DELETE",
      success: function () {
        getData();
      }
    })
    temp.remove();
  });
}
// 修改寄语
ownerSumbit.click(function () {
  var edit = $(".edit-exhibtion").val();
  console.log(edit);
  $.ajax({
    url: "http://localhost:3000/message",
    type: "POST",
    dataType: "json",
    data: {
      id: 1,
      info: edit
    },
    success: function () {
      getMessage();
    }
  })
  $(".edit-exhibtion").val("");
  sendContent.css("display", "none");
})
// 点击“我要留言”
editBtn.click(function () {
  editContent.toggle(".hidden");
})
// 点击“编辑寄语”
sendBtn.click(function () {
  sendContent.toggle(".hidden");
})
// 新增留言
userSumbit.click(function () {
  var username = $(".name").val();
  var content = $(".edit-content textarea").val();
  if (!username || !content) {
    alert("请输入用户名和留言内容~");
    return;
  }
  $.ajax({
    url: "http://localhost:3000/comments",
    type: "POST",
    dataType: "json",
    data: {
      name: username,
      content: content
    },
    success: function (data) {
      getData();
    }
  });
  $(".name").val("");
  $(".edit-content textarea").val("");
});
userCancel.click(function () {
  editContent.css("display", "none");
});